from django.forms.models import model_to_dict
from BloodSpiderAPI.apis.user.utils import utils_model_to_dict as utils_user_model_to_dict
from BloodSpiderAPI.apis.platform.utils import utils_model_to_dict as utils_platform_model_to_dict

def utils_model_to_dict(model, *args, **kwargs):
    """
    将模型转换为字典格式，确保返回数据结构统一
    """
    data = model_to_dict(model)
    # 转换UUID为字符串
    data["account_id"] = str(model.account_id)
    
    # 处理创建人信息
    if model.create_by:
        data["create_by"] = utils_user_model_to_dict(model.create_by)
    else:
        data["create_by"] = None
    
    # 处理当前所属人信息
    if model.current_owner:
        data["current_owner"] = utils_user_model_to_dict(model.current_owner)
    else:
        data["current_owner"] = None

    # 处理平台信息
    if kwargs.get("show_platforms", False):
        # model.platform_accounts.all()
        data["platform"] = [utils_platform_model_to_dict(item) for item in model.platform.all()]
        for item in data["platform"]:
            # 找到这个对应的数据
            platform_account = model.platform_accounts.filter(platform=item["platform_id"], account_id=model.account_id).first()
            item["platform_accounts"] = model_to_dict(platform_account)
            item["platform_accounts"]["status"] = {
                "code": platform_account.status,
                "message": platform_account.get_status_display()
            }
            del item["platform_accounts"]["platform"]
            del item["platform_accounts"]["account"]
            del item["platform_accounts"]["id"]
    else:
        del data["platform"]
    
    # 格式化时间字段
    data["create_time"] = model.create_time.strftime("%Y-%m-%d %H:%M:%S") if model.create_time else None
    data["update_time"] = model.update_time.strftime("%Y-%m-%d %H:%M:%S") if model.update_time else None
    
    return data

def is_valid_id_card(id_card):
    """
    验证身份证号是否有效
    """
    if len(id_card) != 18 or not id_card.isdigit():
        if len(id_card) == 17 and id_card.isdigit():
            return True
        return False
    # 其他验证逻辑...
    return True